package org.example.service.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;


/**
 * @author beikbei
 * @version 1.0
 * @description: TODO
 * @date 2024/5/11 14:52
 */
@Service
public class MyAuthorizationService {
    // 自定义访问控制逻辑，返回值为是否可以访问资源
    private Logger log = LoggerFactory.getLogger(MyAuthorizationService.class);
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        // 获取会话中的用户
        Object principal = authentication.getPrincipal();
        log.debug("检验权限开始");
        log.debug("{}", authentication);
        if (principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            // 获取登录用户的权限
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            // 获取请求URL路径
            String uri = request.getRequestURI();
            log.debug("用户：{} 访问路径: {} 用户权限:{}", userDetails.getUsername(), uri, authorities);
            // 将URI路径封装为权限对象
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(uri);
            return authorities.contains(simpleGrantedAuthority);
        }
        return false;
    }
}
